package com.oocl.ha.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;

import com.oocl.ha.dao.OrderDao;
import com.oocl.ha.entity.Merchant;
import com.oocl.ha.entity.Order;
import com.oocl.ha.entity.User;

@Repository("orderDao")

public class OrderDaoImpl implements OrderDao {

	@PersistenceContext(name = "un")
	private EntityManager em;

	public List<Order> loadAllOrder(int mid) {
		Merchant merchant = new Merchant();
		merchant.setMid(mid);
		String sql = "select o from Order o where o.merchant=:merchant";
		@SuppressWarnings("unchecked")
		List<Order> orders = em.createQuery(sql).setParameter("merchant", merchant).getResultList();
		if (orders.isEmpty()) {
			return null;
		} else {
			return orders;
		}
	}

	public int addOrder(Order order, int mid, int uid) {
		try {
			Merchant merchant = new Merchant();
			merchant.setMid(mid);
			User user = new User();
			user.setUid(uid);
			order.setMerchant(merchant);
			order.setUser(user);
			em.persist(order);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		return 1;
	}

	public int updateOrderTaken(int oid, int taken) {
		try {
			Order order = findOrderById(oid);
			order.setTaken(taken);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		return 1;
	}

	public Order findOrderById(int oid) {
		Order order = em.find(Order.class, oid);
		return order;
	}

	public List<Order> findOrderByUid(int uid) {
		User user = new User();
		user.setUid(uid);		
		String sql = "select o from Order o where o.user=:user";
		@SuppressWarnings("unchecked")
		List<Order> orders = em.createQuery(sql).setParameter("user", user).getResultList();
		if (orders.isEmpty()) {
			return null;
		} else {
			return orders;
		}
	}

}
